
#!/usr/bin/python2
# -*- coding: utf-8 -*-
# vim:ts=4:sw=4:softtabstop=4:smarttab:expandtab:fileencoding=utf-8
'''
        @author: lbergesio,omoya,cbermudo
    @organization: i2CAT, OFELIA FP7

        RAWFile
        Implementes persistence engine to a raw file for RuleTables
'''

try:
   import cPickle as pickle
except:
   import pickle
from threading import Lock

from pelib.resolver.resolver import Resolver

class RAWFile(object):

    #XXX: lbergesio: Is it necessary to use a mutex here?
    _mutex = Lock()

    @staticmethod
    def save(obj, parser, **kwargs):
        if "fileName" not in kwargs:
            raise Exception("FileName is required")

        with RAWFile._mutex:
            with open(kwargs["fileName"], "wb" ) as fileObj:
                cObj = obj.clone()
                pickle.dump(cObj, fileObj)

    @staticmethod
    def load(tableName, resolverMappings, parser, **kwargs):
        if not kwargs["fileName"]:
            raise ValueError("FileName is required")
        with RAWFile._mutex:
            with open(kwargs["fileName"], "r" ) as fileObj:
                table = pickle.load(fileObj)
                table._mutex = Lock()
                table._mappings = resolverMappings
                table._resolver = Resolver(table._mappings)

            if table.name != tableName:
                raise ValueError("Table name mismatch; did you specify the correct file?")
            return table


